import 'package:ac/api/ac_urls.dart';
import 'package:ac/data/ac_user_manager.dart';
import 'package:ac/page/ac_me/ac_me_logic.dart';
import 'package:flutter_datetime_picker/flutter_datetime_picker.dart';
import 'package:get/get.dart';

import '../../model/ac_login_model.dart';
import 'ac_edit_profile_state.dart';

class AcEditProfileLogic extends GetxController {
  final AcEditProfileState state = AcEditProfileState();
  final userInfo = Rxn<Userinfo>();

  @override
  void onInit() {
    // TODO: implement onInit
    super.onInit();
    userInfo.value = AcUserManager.userInfoModel?.userInfo;
    state.nickNameController.text = userInfo.value?.nickname ?? "";
    state.birthday.value = userInfo.value?.birthday ?? "";
  }

  Future<void> updateAvatar() async {
    await Get.find<AcMeLogic>().updateAvatar();
    userInfo.value = AcUserManager.userInfoModel?.userInfo;
    userInfo.refresh();
  }

  // 选择生日
  void selectBirthday() async {
    DateTime now = DateTime.now();
    DateTime eighteenYearsAgo = DateTime(now.year - 18, now.month, now.day);

    DatePicker.showDatePicker(
      Get.context!,
      showTitleActions: true,
      minTime: DateTime(1900, 0, 0),
      maxTime: eighteenYearsAgo,
      onConfirm: (DateTime date) {
        String month = date.month < 10 ? "0${date.month}" : "${date.month}";
        String day = date.day < 10 ? "0${date.day}" : "${date.day}";
        state.birthday.value = "${date.year}-$month-$day";
      },
      currentTime: DateTime.parse(state.birthday.value),
      locale: LocaleType.en,
    );
  }

  Future<void> submit() async {
    var result = await AcUrls.saveUserInfo.post(
      data: {
        "birthday": state.birthday.value,
        "nickname": state.nickNameController.text
      },
    );
    if (result?["code"] == 0) {
      userInfo.value!.birthday = state.birthday.value;
      userInfo.value!.nickname = state.nickNameController.text;
      AcUserManager.updateLoginUserInfo(userInfo.value!);
      Get.back();
    }
  }
}
